#define  _CRT_SECURE_NO_WARNINGS

#include"string.h"

namespace yyh
{
	const size_t string::npos = -1;
	string::string(const char* str)
		:_size(strlen(str))
	{
		_str = new char[_size + 1];
		_capacity = _size;
		strcpy(_str, str);
	}

	string::~string()
	{
		delete[] _str;
		_str = nullptr;
		_size = _capacity = 0;
	}

	void string::reserve(size_t n)
	{
		if (n > _capacity)
		{
			char* temp = new char[n + 1];
			strcpy(temp, _str);
			delete[] _str;
			_str = temp;
			_capacity = n;
		}
	}

	void string::push_back(char ch)
	{
		if (_size == _capacity)
		{
			reserve(_capacity == 0 ? 4 : _capacity * 2);
		}
		_str[_size++] = ch;
		_str[_size] = '\0';
	}

	void string::append(const char* str)
	{
		size_t len = strlen(str);
		if (_size + len > _capacity)
		{
			size_t NewCapacity = 2 * _capacity;
			if (_size + len > NewCapacity)
			{
				NewCapacity = _size + len;
			}
			reserve(NewCapacity);
		}
		strcpy(_str + _size, str);
		_size += len;
	}

	string& string::operator +=(char ch)
	{
		push_back(ch);
		return *this;
	}

	string& string::operator +=(const char* str)
	{
		append(str);
		return *this;
	}

	void string::insert(size_t pos, size_t n, char ch)
	{
		assert(pos <= _size);
		if (_size + n > _capacity)
		{
			size_t NewCapacity = 2 * _capacity;
			if (_size + n > NewCapacity)
			{ 
				NewCapacity = _size + n;
			}
			reserve(NewCapacity);
		}
		size_t end = _size;
		while (end >= pos)
		{
			_str[end + n] = _str[end];
			end--;
		}
		for (int i = 0; i < n; i++)
		{
			_str[pos + i] = ch;
		}
		_size += n;
	}

	void string::insert(size_t pos, const char* str)
	{

	}

	void string::erase(size_t pos, size_t len)
	{

	}

	void test1()
	{
		string s1("hello world");
		cout << s1.c_str() << endl;

		string s2;
		cout << s2.c_str() << endl;

		s1 += 'y';
		s1 += "yyh";
		s1 += "xxxxxxx";
		s1 += "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh";
		cout << s1.c_str() << endl;
	}

	void test2()
	{
		string s1("hello world");
		cout << s1.c_str() << endl;
		s1.insert(6, 3, 'x');
		cout << s1.c_str() << endl;
	}
}